/* ******************************************************************************
 * Copyright Notice:
 * Copyright 2023-2025, Huawei Technologies Co., Ltd. ALL Rights Reserved.
 *
 * Warning: This computer software sourcecode is protected by copyright law
 * and international treaties. Unauthorized reproduction or distribution
 * of this sourcecode, or any portion of it, may result in severe civil and
 * criminal penalties, and will be prosecuted to the maximum extent
 * possible under the law.
 * *******************************************************************************
 */
package com.android.server.am;

import android.app.SharedPreferencesHelper;

import java.io.File;
import java.util.HashSet;
import java.util.Set;

public class RootManager {

    private static final String WHITELIST_KEY = "packages";

    private static final String WHITELIST_PATH_SYSTEM = "/system/etc/packages_priv.xml";
    private static final String WHITELIST_PATH_USER = "/data/system/packages_priv.xml";

    private final SharedPreferencesHelper mConfigSystem;
    private final SharedPreferencesHelper mConfigUser;

    private final Set<String> mListSystem;
    private final Set<String> mListUser;

    public RootManager() {
        mConfigSystem = new SharedPreferencesHelper(new File(WHITELIST_PATH_SYSTEM));
        mConfigUser = new SharedPreferencesHelper(new File(WHITELIST_PATH_USER));
        mListSystem = new HashSet<>();
        mListUser = new HashSet<>();
    }

    public void addToWhiteList(String packageName) {
        mListUser.add(packageName);
        mConfigUser.putStringSet(WHITELIST_KEY, mListUser);
    }

    public void removeFromWhiteList(String packageName) {
        mListUser.remove(packageName);
        mConfigUser.putStringSet(WHITELIST_KEY, mListUser);
    }

    public void clearWhiteList() {
        mListUser.clear();
        mConfigUser.putStringSet(WHITELIST_KEY, mListUser);
    }

    public void loadWhiteList() {
        mListSystem.addAll(mConfigSystem.getStringSet(WHITELIST_KEY, new HashSet<>()));
        mListUser.addAll(mConfigUser.getStringSet(WHITELIST_KEY, new HashSet<>()));
    }

    public boolean isInWhiteList(String packageName) {
        return mListSystem.contains(packageName) || mListUser.contains(packageName);
    }

    @Override
    public String toString() {
        StringBuilder result = new StringBuilder();
        result.append("System Root App List:").append("\n");
        for (String name : mListSystem) {
            result.append(name).append("\n");
        }
        result.append("\n");
        result.append("User Root App List:").append("\n");
        for (String name : mListUser) {
            result.append(name).append("\n");
        }
        return result.toString();
    }
}